<!--标准产品-->
<template>
  <div class="product_management_container">
    <div class="search_box">
      <!-- <el-button type="primary" class="fl" @click="showPopup">新增</el-button> -->
      <div class="btn btn_add" @click="showPopup('ruleForm')">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">新建产品</span>
      </div>
      <!-- <div class="btn btn_add">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">批量导入</span>
      </div>

      <div class="downloadModel btn">
        <i></i>
        <span>下载模板</span>
      </div> -->
      <div class="fr" >
        <el-form :model="searchForm" :inline="true" class="searchForm"  >
          <el-form-item size="small" style="width:150px;">
            <el-select v-model="searchForm.courseId" clearable placeholder="大类">
              <el-option v-for="(item,key) in courseList" :key="key" :label="item.courseName" :value="item.courseId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item size="small" style="width:150px;">
            <el-select v-model="searchForm.isActive" clearable placeholder="状态">
              <el-option key="1" value="1" label="开售"></el-option>
              <el-option key="0" value="0" label="停售"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item size="small" style="width: 220px; margin-right: 0;">
            <el-input placeholder="输入课程产品名称/编号" size="small" v-model="searchForm.searchValue" @keyup.enter.native="searchData(searchValue)">
              <div slot="append" class="btn_search" @click="searchData(searchValue)">查询</div>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="clear"></div>
    </div>
    
    <div class="table_box">
      <adminTable :tableHead="tableHead" :tableData="tableData"></adminTable>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.curPage"
        :page-sizes="[10, 20, 50]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalRows">
      </el-pagination>
    </div>

    <transition name="el-fade-in-linear">
      <div>
        
        <div class="popup-container" v-show="popupState.showStatus">
          <div class="popup">
            <i class="el-icon-error icon_close" @click="popupState.showStatus = false;"></i>
            <div class="title">{{popupState.popupName}}</div>

            <div class="content">
              <el-form :model="formData" ref="ruleForm" :rules="rules" label-position="left"  style=""
                :inline="true" class="form"  :disabled="checkStatus">
                <div >
                  
                  <div class="box">
                    <h6 class="sub_title">基本信息</h6>
                    <div class="form_box">
                      <el-form-item label="大类 : "  prop="courseId"  size="small" class="fl">
                        <el-select v-model="formData.courseId" placeholder="选择" style="width: 170px;" @change="changeCourse">
                          <el-option v-for="(item,key) in courseList" :key="key" :label="item.courseName" :value="item.courseId">
                          </el-option>
                        </el-select>
                      </el-form-item>
                      
                      <el-form-item label="大类编号 : " prop="courseCode" size="small" class="fl ">
                        {{formData.courseCode}}
                      </el-form-item>

                      <el-form-item label="课程产品编号 : "  prop="productCode" size="small" class="fl">
                        {{formData.productCode}}
                      </el-form-item>
                      <el-form-item label="课程产品名称 : " prop="productName" size="small" class="fl no_margin_right">
                        <el-input v-model="formData.productName" style="width: 170px;" autocomplete="off" placeholder=""></el-input>
                      </el-form-item>
                      <div class="clear"></div>
                    </div>
                  </div>

                  <div class="box">
                    <h6 class="sub_title">课时信息</h6>
                    <div class="form_box">
                      <el-form-item label="最低开班人数(人) : " prop="minPerson"  size="small" class="fl">
                        <el-input v-model="formData.minPerson" style="width: 85px;"  placeholder=""></el-input>
                      </el-form-item>
                      
                      <el-form-item label="满班人数(人) : " prop="maxPerson" size="small" class="fl ">
                        <el-input v-model="formData.maxPerson" style="width: 85px;"  placeholder=""></el-input>
                      </el-form-item>

                      <el-form-item label="周数(周) : " prop="weekMun" size="small" class="fl">
                        <el-input v-model="formData.weekMun" style="width: 85px;"  placeholder=""></el-input>
                      </el-form-item>
                      <el-form-item label="总课时(课时) : " prop="totalHour" size="small" class="fl no_margin_right">
                        <el-input v-model="formData.totalHour" style="width: 85px;"  placeholder=""></el-input>
                      </el-form-item>
                      <div class="clear"></div>
                    </div>

                    <div class="form_box multi" style="padding-top: 0px;">
                      <div class="item fl" 
                        v-for="(item, index) in formData.productSubjectList" 
                        :key="index"
                      >
                        <el-input placeholder="" size="small"  v-model="formData.productSubjectList[index].classHour" class="input-with-select">
                          <el-select v-model="item.subjectId" @change="(e)=>changeSubject(e, index)" prop="subjectId" style="width: 100px;" slot="prepend" placeholder="科目选择">
                            <el-option v-for="(item,key) in subjectList" :key="key" :label="item.subjectName" :value="item.subjectId">
                            </el-option>
                          </el-select>
                          <span slot="append" class="append">课时/周</span>
                        </el-input>
                        <i class="add_input el-icon-circle-plus-outline" 
                          v-if="index == formData.productSubjectList.length - 1 && !checkStatus"
                          @click="addInput"
                        >
                        </i>
                        <!-- <i class="add_input el-icon-circle-plus-outline" 
                          v-if="index == formData.productSubjectList.length - 1 && !checkStatus"
                          @click="addInput"
                        >
                        </i> -->
                      </div>
                      <div class="clear"></div>
                    </div>
                  </div>

                  <div class="box">
                    <h6 class="sub_title">价格信息</h6>
                    <div class="form_box">
                      <el-form-item label="课程指导价(元) : " prop="productPrice"  size="small" class="fl">
                        <el-input v-model="formData.productPrice" style="width: 95px;"  placeholder=""></el-input>
                      </el-form-item>
                      
                      <el-form-item label="餐费(元) : " prop="mealsPrice" size="small" class="fl ">
                        <el-input v-model="formData.mealsPrice" style="width: 95px;"  placeholder=""></el-input>
                      </el-form-item>

                      <el-form-item label="杂费(元) : " prop="incidentalPrice" size="small" class="fl">
                        <el-input v-model="formData.incidentalPrice" style="width: 95px;"  placeholder=""></el-input>
                      </el-form-item>
                      <el-form-item label="其它费用(元) : "  size="small" prop="otherPrice" class="fl no_margin_right">
                        <el-input v-model="formData.otherPrice" style="width: 90px;"  placeholder="其它费用"></el-input>
                      </el-form-item>
                      <div class="clear"></div>
                        
                      <div class="total_price">
                        标准总价：￥{{totalPrice}}
                      </div>
                    </div>
                  </div>

                  <div class="box">
                    <h6 class="sub_title">使用信息</h6>
                    <div class="form_box" style="line-height: 32px;">
                      <el-form-item  size="small" prop="productRemark" class="fl">
                        <el-input v-model="formData.productRemark" style="width: 300px" autocomplete="off" placeholder="课程使用描述"></el-input>
                      </el-form-item>

                      <upLoadFile 
                        v-if="!checkStatus"
                        :message="checkStatus? '附件' : '添加附件'" 
                        class="upload_file fl"
                        ref="upload_dom"
                        :rules="upload_rules"
                        @fun="passe" 
                        @progress="return_back"
                        
                      >
                      </upLoadFile>
                      <span style="font-size: 12px;color: #77A4FF;" v-if="checkStatus">附件 : </span>
                      <!-- <span class="file_name" v-if="!checkStatus">{{filesName}}</span> -->
                      <span class="file_name"  @click="downloadFile" style="cursor: pointer;">{{filesName}}</span>
                      <div class="clear"></div>
                    </div>
                  </div>

                  <div class="box">
                    <h6 class="sub_title">授课信息</h6>
                    <div class="form_box" style="display:flex; align-items:center;">
                      <el-radio v-model="formData.associationMode" label="1">面授</el-radio>
                      <el-radio v-model="formData.associationMode" label="2">在线</el-radio>
                      <el-form-item label="关联网课 : "  v-if="formData.associationMode == 2"  size="small" >
                        <el-select v-model="formData.associationSubjectPackageId" placeholder="选择" style="width: 170px;" @change="changeCourse">
                          <el-option v-for="(item,key) in subjectPackageList" :key="key" :label="item.subjectPackageName" :value="item.subjectPackageId">
                          </el-option>
                        </el-select>
                      </el-form-item>

                      <el-form-item label="课程介绍 : "  size="small" style="width: 350px"  class="no_margin_right">
                        <el-input type="textarea" v-model="formData.productIntroductions" style="width: 270px" autosize maxlength="30" show-word-limit  placeholder="课程介绍"></el-input>
                      </el-form-item>
                    </div>
                  </div>


                </div>

              </el-form>

              <div class="btn_box">
                <div class="btn btn_add" v-if="popupState.popupName == '新建课程产品'" @click="submitAdd('ruleForm')">
                  <span class="btn_txt">保存</span>
                </div>

                <div class="btn btn_add" v-if="popupState.popupName == '编辑课程产品'" @click="submitEdit('ruleForm')">
                  <span class="btn_txt">保存</span>
                </div>
              </div>

            </div>
          </div>
        </div>

        <div class="popup-container" v-show="showLog">
          <div class="popup">
            <i class="el-icon-error icon_close" @click="showLog = false;"></i>
            <div class="title">日志</div>

            <div class="content">

            </div>
          </div>
        </div>

      </div>
    </transition>
  </div>
</template>

<style>
.product_management_container .popup .el-form-item--small.el-form-item{
  width: auto;
}

.product_management_container .popup .el-form-item__label {
  font-size: 12px !important;
}

.product_management_container .popup .el-input-group__append {
  padding: 0 8px;
}

.product_management_container .el-input-group__prepend {
  background: none !important;
}

.product_management_container .form_box .item {
  width: 30.1%;
  margin-right: 4.8%;
  margin-top: 10px;
  position: relative;
}
.add_input {
  position: absolute;
  transform: translateY(-50%);
  top: 50% !important;
  color: #87AEFF;
  cursor: pointer;
  /* margin-left: 6px; */
  right: -18px;
}
.product_management_container .form_box .item:nth-child(3n) {
  margin-right: 0 !important;
}

.product_management_container .multi {
  /* display: flex; */
}

</style>
<style scoped>

.downloadModel i {
  position: relative;
  top: 1px;
}

.product_management_container .btn_add i {
  margin-right: 5px;
  margin-left: 10px;
}

.product_management_container .file_name {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}

.total_price {
  font-size: 18px;
  color: #E02020;
  margin-top: 10px;
}


.popup .box {
  box-shadow:0px 2px 4px 0px rgba(225,225,225,0.5);
  margin-bottom: 15px;
}

.popup .box .sub_title {
  height:30px;
  background:#F0F2F5;
  line-height: 30px;
  color: #FC8434;
  font-size: 14px;
  font-weight: normal;
  padding-left: 20px;
}

.popup .content{
  padding-top: 5px !important;
}
.popup .title {
  border-bottom: none;
}

.box .form_box {
  padding: 10px 20px;
}


.btn_box {
  margin-top: 20px;
}
.popup .content {
  padding-top: 30px;
}
</style>

<script>
import adminTable from '@/components/assembly/adminTable'
import upLoadFile from '@/components/assembly/upLoadFile'
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("standardProduct");
export default {
  name: 'standardProduct',
  data() {
    return {
      productId: '',
      checkStatus: false,
      showLog: false,
      isLogin: false,
      popupState: {
        showStatus: false,
        popupName: '新增产品',
      },
      page: {
        curPage: 1,
        pageSize: 10,
        totalRows: 0,
      },
      searchForm: {
        courseId: '',
        isActive: '',
        searchValue: '',
      },
      formData: {
        associationMode: '1',
        associationSubjectPackageId: '',
        productIntroductions: '',
        courseId: '',
        productCode: '',
        courseCode: '',
        productName: '',
        minPerson: '',
        maxPerson: '',
        weekMun: '',
        totalHour: '',
        productPrice: '',
        mealsPrice: '',
        incidentalPrice: '',
        otherPrice: '',
        productRemark: '',
        fileIds: '',
        productSubjectList: [
          {
            classHour: "",
            id: "",
            productId: "",
            subjectId: "",
            subjectName: ""
          }
        ]
      },
      searchValue: '',

      tableHead: {
        // border: true,
        // order: true,
        switch: {
          fun: this.switchFun,
        },
        operation_width: '220px',
        setFunction: [
          // {
          //   fun: this.tableLog,
          //   name: "日志"
          // },
          {
            fun: this.tableDetail,
            name: "详情"
          },
          {
            // showState: "0",
            // hideKey: "flag",
            fun: this.tableEdit,
            name: "编辑"
          },
          {
            fun: this.tableDelete,
            name: "删除"
          },
        ],
        data: [
          {
            name: '课程产品名称',
            key: 'productName',
            align: 'center',
            width: '140px',
          },
          {
            name: "课程产品编号",
            key: "productCode",
            align: "center",
            width: '60px'
          },
          {
            name: "大类",
            key: "courseName",
            align: "center"
          },
          {
            name: "总课时数",
            key: "totalHour",
            align: "center",
            // width: '50'
          },
          {
            name: "周数",
            key: "weekMun",
            align: "center",
            width: '50'
          },
          {
            name: "课程指导价(元)",
            key: "productPrice",
            align: "center",
          },
          {
            name: "餐费(元)",
            key: "mealsPrice",
            align: "center"
          },
          {
            name: "杂费(元)",
            key: "incidentalPrice",
            align: "center",
          },
          {
            name: "标准总价(元)",
            key: "totalPrice",
            align: "center",
          },
        ]
      },
      tableData: [],

      courseList: [],
      subjectList: [],

      subjectPackageList: [],

      filesNameList: [],
      filesName: '',
      fileIdsList: [],

      rules: {
        accountName: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
        ],
        employeesName: [
          { required: true, message: '请输入产品姓名', trigger: 'blur' },
        ],
        entryType: [
          { required: true, message: '请选择入职类型', trigger: 'change' },
        ],
        entryTime: [
          { required: true, message: '请选择入职时间', trigger: 'change' },
        ],
        accountPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {pattern: /^1[34578]\d{9}$/, message: '手机号格式错误'}
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' },
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' },
        ],
        positionCode: [
          { required: true, message: '请选择职位', trigger: 'change' },
        ],
        rankCode: [
          { required: true, message: '请选择职级', trigger: 'change' },
        ],
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
        ],
        schoolId: [
          { required: true, message: '请选择校区', trigger: 'change' },
        ],
      },

      upload_rules: [{
        "rule": ['txt', 'doc', 'pdf', 'xlsx', 'xls'],
        "message": "文件类型必须为.txt, .doc, .pdf, .xlsx, .xls"
      }],
    }
  },
  created() {
    this.initData();
    this.initSelect();
    this.queryAllSubjectPackage();
  },
  // watch: {
  //   mapPowerList: {
  //     handler(newName, oldName) {
  //     },
  //     immediate: true,
  //     deep: true
  //   }
  // },
  
  methods: {
    ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),

    initData(searchForm) {
      // console.log(searchValue)
      let searchValue = searchForm || this.searchForm || '';
      let data = searchValue;
      data.curPage = this.page.curPage;
      data.pageSize = this.page.pageSize;

      this.post({
        API: 'selectBmProductPageList',
        data: data
      }).then(res => {
        this.tableData = res.data;
        this.tableData.forEach(item => {
          item.isActive == 1 ? item.isActive = true : false
        })

        this.page = res.page;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    initSelect() {
      this.post({
        API: 'queryAllCourseType',
        data: {}
      }).then(res => {
        this.courseList = res;
      }).catch(err => {
        this.$message.error(err);
      })

      this.post({
        API: 'queryAllSubject',
        data: {}
      }).then(res => {
        this.subjectList = res;
      }).catch(err => {
        this.$message.error(err);
      })
      

    },

    // 新增提交
    submitAdd(formName) {

      let data = this.formData;
      if(data.mealsPrice == '') {
        data.mealsPrice = '0'
      }
      if(data.incidentalPrice == '') {
        data.incidentalPrice = '0'
      }
      data.totalPrice = this.totalPrice.toString();

      data.fileIds = this.fileIdsList.join(',')

      let totalHour = data.totalHour
      let flag = true;
      this.formData.productSubjectList.forEach(item => {
        if(Number(item.classHour) > Number(totalHour)) {
          this.$message.error('单科课时不得超过总课时')
          flag = false;
        }
      })

      this.$refs[formName].validate((valid) => {
        if (valid && flag) {
          this.post({
            API: 'insert',
            data: data
          }).then(res => {
            console.log(res)
            if(res == 1) {
              this.$message.success('新建成功')
              this.initData();
              this.popupState.showStatus = false;
            }
          }).catch(err => {
            this.$message.error(err);
          })
        } else {
          // console.log('error submit!!');
          return false;
        }
      });

      
    },

    // 编辑提交
    submitEdit(rowData) {
      let data = this.formData
      if(data.mealsPrice == '') {
        data.mealsPrice = '0'
      }
      if(data.incidentalPrice == '') {
        data.incidentalPrice = '0'
      }
      data.fileIds = this.fileIdsList.join(',')
      data.totalPrice = this.totalPrice.toString();
      data.productId = this.productId;
      data.dataId = this.productId;

      this.post({
        API: 'update',
        data: data
      }).then(res => {
        this.$message.success('修改成功');
        this.initData();
        this.popupState.showStatus = false;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    switchFun(rowData) {
      let isActive
      let msg
      if(rowData.row.isActive == true) {
        isActive = 1
      }else{
        isActive = 0
      }
      let data = {
        productId: rowData.row.productId,
        dataId: rowData.row.productId,
        isActive: isActive,
      }
      this.post({
        API: 'updateIsActive',
        data: data
      }).then(res => {
        if(isActive == 1) {
          this.$message.success('已开售')
        }else{
          this.$message.warning('已停售')
        }
      }).catch(err => {
        this.$message.error(err);
      })
    },

    // 表格编辑 回显
    tableEdit(rowData) {
      this.checkStatus = false;
      this.productId = rowData.row.productId;
      let data = {
        id: this.productId,
      }
      this.formGet({
        API: 'selectById',
        data: data
      }).then(res => {
        this.popupState = {
          popupName: '编辑课程产品',
          showStatus: true,
        }
        this.$refs['ruleForm'].resetFields();
        this.formData = res;
        if(!this.formData.associationMode) {
          this.formData.associationMode = '1'
        }
        this.filesName = res.fileName;
        
      }).catch(err => {
        this.$message.error(err);
      })
    },

    tableDetail(rowData) {
      this.productId = rowData.row.productId;
      let data = {
        id: this.productId,
      }
      this.formGet({
        API: 'selectById',
        data: data
      }).then(res => {
        this.popupState = {
          popupName: '课程产品详情',
          showStatus: true,
        }
        this.checkStatus = true;
        this.formData = res;
        this.filesName = res.fileName;
        
      }).catch(err => {
        this.$message.error(err);
      })
    },

    tableLog(rowData) {
      this.showLog = true;
    },



    // 表格删除
    tableDelete(rowData) {
      let productId = rowData.row.productId;
      let data = {
        id: productId,
        dataId: productId,
      }

      this.$confirm('是否删除该产品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formGet({
          API: 'deleteById',
          data: data
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.initData();
        }).catch(err => {
          this.$message.error(err);
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });

      
      
    },

    showPopup(formName) {
      this.$refs[formName].resetFields();   // 初始化
      this.filesName = '';
      this.checkStatus = false;
      this.formData.productSubjectList = [
        {
          classHour: "",
          id: "",
          productId: "",
          subjectId: "",
          subjectName: ""
        }
      ]
      this.popupState = {
        showStatus: true,
        popupName: '新建课程产品',
      }
    },
    searchData(searchValue) {
      this.page.curPage = 1;
      this.initData(searchValue)
    },

    // 更改大类获取大类编号
    changeCourse(e) {
      this.courseList.forEach(item => {
        if(item.courseId == e) {
          this.formData.courseCode = item.courseCode
        }
      })

      this.formGet({
        API: 'queryMaxProductCode',
        data: {
          courseCode: this.formData.courseCode
        }
      }).then(res => {
        this.formData.productCode = res
      }).catch(err => {
        this.$message.error(err);
      })
    },

    // 更改科目获取科目名称
    changeSubject(e, index) {
      this.subjectList.forEach(item => {
        if(item.subjectId == e) {
          this.formData.productSubjectList[index].subjectName = item.subjectName;
        }
      })
    },

    addInput() {
      let obj = {
        classHour: "",
        id: "",
        productId: "",
        subjectId: "",
        subjectName: ""
      }

      this.formData.productSubjectList.push(obj);
    },

    downloadFile() {
      let fileId = this.formData.fileIds;

      window.open(`http://39.105.125.149:8060/bmOssFile/downloadFileForDisk?fileId=${fileId}`)

    },

    passe(e) {
      if (e.error) {
        this.$message.error(e.error)
        return false
      }
      if (e.success) {
        console.log(e.success)
        this.fileIdsList.push(e.success.fileId)
        this.$message.success('上传成功');
        this.filesNameList.push(e.success.fileOriname)
        this.filesName = this.filesNameList.join('  ');
      }else{
        this.$message.error('上传失败');
      }
    },
    return_back(e) {
    },

    queryAllSubjectPackage() {
      this.post({
        API: 'queryAllSubjectPackage',
        data: {}
      }).then(res => {
        this.subjectPackageList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },


    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page.curPage = val;
      this.initData();
    }
    
  },
  computed: {
    ...mapState([
    ]),
    // ...mapGetters(["selectedIds"]),

    totalPrice() {
      let data = this.formData;
      return Number(data.productPrice) + 
             Number(data.mealsPrice) + 
             Number(data.incidentalPrice) + 
             Number(data.otherPrice);
    }
  },
  components: {
    adminTable,
    upLoadFile,
  },
}

</script>